﻿namespace TriangleGames.TrainResEditor
{
    using TriangleGames.TrainRes;
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using UnityEditor;
    using UnityEngine;

    public class FsmBuilder
    {
        private static FsmTemplate clipboard;

        public FsmStateAction AddAction(FsmState state, System.Type actionType)
        {
            if (state == null)
            {
                return null;
            }
            FsmEditor.RegisterUndo("添加动作");
            FsmStateAction item = (FsmStateAction) Activator.CreateInstance(actionType);
            state.Actions = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmStateAction>(state.Actions, item);
            item.Init(state);
            item.Reset();
            state.SaveActions();
            FsmEditor.SetFsmDirty(true, false);
            return item;
        }

        public FsmEvent AddEvent(Fsm fsm, FsmEvent fsmEvent)
        {
            if (fsmEvent == null)
            {
                return null;
            }
            foreach (FsmEvent event2 in fsm.Events)
            {
                if (event2.Name == fsmEvent.Name)
                {
                    return event2;
                }
            }
            fsm.Events = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmEvent>(SelectedFsm.Events, fsmEvent);
            Array.Sort<FsmEvent>(fsm.Events);
            FsmEditor.SetFsmDirty(fsm, true, false);
            return fsmEvent;
        }

        public FsmEvent AddEvent(string name, [Optional, DefaultParameterValue(true)] bool undo)
        {
            if (undo)
            {
                FsmEditor.RegisterUndo("添加事件");
            }
            FsmEvent fsmEvent = FsmEvent.GetFsmEvent(name);
            return this.AddEvent(SelectedFsm, fsmEvent);
        }

        public static void AddFsmToSelected()
        {
            GameObject[] gameObjects = Selection.gameObjects;
            if (gameObjects.Length != 0)
            {
                if (gameObjects.Length > 1)
                {
                    if (!EditorUtility.DisplayDialog("添加状态机", "添加状态机到多个对象?", "确定", "取消"))
                    {
                        return;
                    }
                    FsmEditor.RegisterSceneUndo("添加状态机到选定对象");
                    foreach (GameObject obj2 in gameObjects)
                    {
                        string str = FsmEditorUtility.GenerateUniqueFsmName(obj2);
                        DoAddFsmComponent(obj2).Fsm.Name = str;
                    }
                }
                else if (Selection.activeGameObject != null)
                {
                    string str2 = FsmEditorUtility.GenerateUniqueFsmName(Selection.activeGameObject);
                    TrainResFSMCore objectToUndo = DoAddFsmComponent(Selection.activeGameObject);
                    objectToUndo.Fsm.Name = str2;
                    FsmEditor.SelectFsm(objectToUndo.Fsm);
                    FsmEditor.SelectState(objectToUndo.Fsm.States[0], false);
                    Undo.RegisterCreatedObjectUndo(objectToUndo, "添加状态机到选定对象");
                }
                FsmEditor.RebuildFsmList();
            }
        }

        public void AddGlobalTransition(FsmState state, FsmEvent fsmEvent)
        {
            FsmEditor.RegisterUndo("添加全局过渡");
            FsmTransition transition2 = new FsmTransition();
            transition2.ToState = state.Name;
            transition2.FsmEvent = fsmEvent;
            FsmTransition item = transition2;
            SelectedFsm.GlobalTransitions = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmTransition>(SelectedFsm.GlobalTransitions, item);
            FsmEditor.EventManager.UpdateUseCount();
            FsmEditor.SetFsmDirty(true, false);
        }

        public FsmState AddState(Vector2 position)
        {
            FsmEditor.RegisterUndo("添加状态");
            FsmState state2 = new FsmState(SelectedFsm);
            state2.Name = FsmEditorSettings.NewStateName;
            FsmState state = state2;
            state.Name = GenerateUniqueStateName(state, state.Name);
            SelectedFsm.States = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmState>(SelectedFsm.States, state);
            UpdateStateSize(state);
            UpdateStatePosition(state, position);
            if (SelectedFsm.States.Length == 1)
            {
                this.SetStartState(state.Name);
            }
            FsmEditor.GraphView.UpdateCanvasSize();
            FsmEditor.SetFsmDirty(true, false);
            return state;
        }

        public static Fsm AddTemplate(FsmTemplate fsmTemplate)
        {
            if ((fsmTemplate == null) || (FsmEditor.SelectedFsmGameObject == null))
            {
                return null;
            }
            FsmEditor.RegisterSceneUndo("添加模板");
            return DoAddTemplate(FsmEditor.SelectedFsmGameObject, fsmTemplate);
        }

        public static Fsm AddTemplateToSelected(FsmTemplate fsmTemplate)
        {
            if (fsmTemplate == null)
            {
                return null;
            }
            GameObject[] gameObjects = Selection.gameObjects;
            if (gameObjects.Length == 0)
            {
                return null;
            }
            if ((gameObjects.Length > 1) && !EditorUtility.DisplayDialog("添加状态机模板", "添加状态机模板到多个对象?", "确定", "取消"))
            {
                return null;
            }
            FsmEditor.RegisterSceneUndo("添加状态机模板到选定对象");
            return DoAddTemplateToSelected(fsmTemplate);
        }

        public FsmTransition AddTransition(FsmState state)
        {
            return this.AddTransition(state, string.Empty, null);
        }

        public FsmTransition AddTransition(FsmState state, string toState, FsmEvent fsmEvent)
        {
            FsmEditor.RegisterUndo("添加过渡");
            FsmTransition transition2 = new FsmTransition();
            transition2.ToState = toState;
            transition2.FsmEvent = fsmEvent;
            FsmTransition item = transition2;
            state.Transitions = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmTransition>(state.Transitions, item);
            UpdateStateSize(state);
            FsmEditor.EventManager.UpdateUseCount();
            FsmEditor.SetFsmDirty(true, false);
            return item;
        }

        private static float CalculateStateWidth(FsmState state)
        {
            float x = FsmEditorStyles.StateTitleBox.CalcSize(new GUIContent(state.Name)).x;
            foreach (FsmTransition transition in state.Transitions)
            {
                float num2 = FsmEditorStyles.TransitionBox.CalcSize(new GUIContent(transition.EventName)).x;
                if (num2 > x)
                {
                    x = num2;
                }
            }
            foreach (FsmTransition transition2 in state.Fsm.GlobalTransitions)
            {
                if (transition2.ToState == state.Name)
                {
                    float num3 = FsmEditorStyles.GlobalTransitionBox.CalcSize(new GUIContent(transition2.EventName)).x;
                    if (num3 > x)
                    {
                        x = num3;
                    }
                }
            }
            if (FsmEditorSettings.ShowCommentsInGraphView && !string.IsNullOrEmpty(state.Description))
            {
                float num4 = FsmEditorStyles.StateTitleBox.CalcSize(new GUIContent(state.Description)).x;
                if (num4 > x)
                {
                    x = (x + num4) * 0.5f;
                }
            }
            x += 20f;
            if (x > FsmEditorSettings.StateMaxWidth)
            {
                x = FsmEditorSettings.StateMaxWidth;
            }
            if (x < 100f)
            {
                x = 100f;
            }
            return x;
        }

        public bool CanPaste()
        {
            return (((clipboard != null) && (clipboard.fsm != null)) && (clipboard.fsm.States.Length > 0));
        }

        public void ClearBreakpoints()
        {
            if (SelectedFsm != null)
            {
                FsmEditor.RegisterUndo("清除断点");
                foreach (FsmState state in SelectedFsm.States)
                {
                    state.IsBreakpoint = false;
                }
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        private static FsmEvent[] CopyEvents(IEnumerable<FsmEvent> events)
        {
            List<FsmEvent> list = new List<FsmEvent>();
            foreach (FsmEvent event2 in events)
            {
                list.Add(new FsmEvent(event2));
            }
            return list.ToArray();
        }

        public static void CopyFsmToClipboard(Fsm fsm)
        {
            if (fsm != null)
            {
                if (clipboard == null)
                {
                    CreateClipboard();
                }
                CopyFsmToTemplate(fsm, clipboard);
            }
        }

        public static void CopyFsmToTemplate(Fsm fsm, FsmTemplate template)
        {
            Fsm fsm2 = new Fsm();
            fsm2.Name = fsm.Name;
            fsm2.Description = fsm.Description;
            fsm2.Watermark = fsm.Watermark;
            fsm2.StartState = fsm.StartState;
            fsm2.States = CopyStates(fsm.States);
            fsm2.GlobalTransitions = CopyTransitions(fsm.GlobalTransitions);
            fsm2.Events = CopyEvents(fsm.Events);
            fsm2.Variables = CopyVariables(fsm.Variables);
            template.fsm = fsm2;
        }

        private static FsmState CopyState(FsmState state)
        {
            FsmState state3 = new FsmState(null);
            state3.Name = state.Name;
            state3.ColorIndex = state.ColorIndex;
            state3.Description = state.Description;
            state3.HideUnused = state.HideUnused;
            state3.Transitions = CopyTransitions(state.Transitions);
            state3.Position = new Rect(state.Position);
            FsmState state2 = state3;
            state2.CopyActionData(state);
            return state2;
        }

        private static FsmState[] CopyStates(IEnumerable<FsmState> states)
        {
            List<FsmState> list = new List<FsmState>();
            foreach (FsmState state in states)
            {
                list.Add(CopyState(state));
            }
            return list.ToArray();
        }

        public static void CopyStatesToClipboard(List<FsmState> states)
        {
            if (clipboard == null)
            {
                CreateClipboard();
            }
            CopyStatesToTemplate(states, clipboard);
        }

        public static void CopyStatesToTemplate(List<FsmState> states, FsmTemplate template)
        {
            Fsm fsm = new Fsm();
            fsm.States = CopyStates(states);
            template.fsm = fsm;
            foreach (FsmState state in states)
            {
                if (state.Fsm.StartState == state.Name)
                {
                    template.fsm.StartState = state.Name;
                }
            }
            List<FsmTransition> list = new List<FsmTransition>();
            foreach (FsmState state2 in states)
            {
                foreach (FsmTransition transition in state2.Fsm.GlobalTransitions)
                {
                    if (transition.ToState == state2.Name)
                    {
                        list.Add(CopyTransition(transition));
                    }
                }
            }
            template.fsm.GlobalTransitions = list.ToArray();
            template.fsm.Variables = CopyStateVariables(states, SelectedFsm.Variables);
            Vector2 vector = new Vector2(float.PositiveInfinity, float.PositiveInfinity);
            foreach (FsmState state3 in template.fsm.States)
            {
                vector.x = Mathf.Min(state3.Position.x, vector.x);
                vector.y = Mathf.Min(state3.Position.y, vector.y);
            }
            foreach (FsmState state4 in template.fsm.States)
            {
                state4.Position = new Rect(state4.Position.x - vector.x, state4.Position.y - vector.y, state4.Position.width, state4.Position.height);
            }
            EditorUtility.SetDirty(template);
        }

        private static FsmVariables CopyStateVariables(List<FsmState> states, FsmVariables variables)
        {
            List<string> variablesUsedByStates = (List<string>) FsmEditor.VariableManager.GetVariablesUsedByStates(states);
            List<FsmFloat> list2 = new List<FsmFloat>();
            List<FsmInt> list3 = new List<FsmInt>();
            List<FsmBool> list4 = new List<FsmBool>();
            List<FsmGameObject> list5 = new List<FsmGameObject>();
            List<FsmColor> list6 = new List<FsmColor>();
            List<FsmVector3> list7 = new List<FsmVector3>();
            List<FsmRect> list8 = new List<FsmRect>();
            List<FsmQuaternion> list9 = new List<FsmQuaternion>();
            List<FsmObject> list10 = new List<FsmObject>();
            List<FsmMaterial> list11 = new List<FsmMaterial>();
            List<FsmTexture> list12 = new List<FsmTexture>();
            List<FsmString> list13 = new List<FsmString>();
            foreach (FsmFloat num in variables.FloatVariables)
            {
                if (variablesUsedByStates.Contains(num.Name))
                {
                    list2.Add(new FsmFloat(num));
                }
            }
            foreach (FsmInt num2 in variables.IntVariables)
            {
                if (variablesUsedByStates.Contains(num2.Name))
                {
                    list3.Add(new FsmInt(num2));
                }
            }
            foreach (FsmBool @bool in variables.BoolVariables)
            {
                if (variablesUsedByStates.Contains(@bool.Name))
                {
                    list4.Add(new FsmBool(@bool));
                }
            }
            foreach (FsmGameObject obj2 in variables.GameObjectVariables)
            {
                if (variablesUsedByStates.Contains(obj2.Name))
                {
                    list5.Add(new FsmGameObject(obj2));
                }
            }
            foreach (FsmColor color in variables.ColorVariables)
            {
                if (variablesUsedByStates.Contains(color.Name))
                {
                    list6.Add(new FsmColor(color));
                }
            }
            foreach (FsmVector3 vector in variables.Vector3Variables)
            {
                if (variablesUsedByStates.Contains(vector.Name))
                {
                    list7.Add(new FsmVector3(vector));
                }
            }
            foreach (FsmRect rect in variables.RectVariables)
            {
                if (variablesUsedByStates.Contains(rect.Name))
                {
                    list8.Add(new FsmRect(rect));
                }
            }
            foreach (FsmQuaternion quaternion in variables.QuaternionVariables)
            {
                if (variablesUsedByStates.Contains(quaternion.Name))
                {
                    list9.Add(new FsmQuaternion(quaternion));
                }
            }
            foreach (FsmObject obj3 in variables.ObjectVariables)
            {
                if (variablesUsedByStates.Contains(obj3.Name))
                {
                    list10.Add(new FsmObject(obj3));
                }
            }
            foreach (FsmMaterial material in variables.MaterialVariables)
            {
                if (variablesUsedByStates.Contains(material.Name))
                {
                    list11.Add(new FsmMaterial(material));
                }
            }
            foreach (FsmTexture texture in variables.TextureVariables)
            {
                if (variablesUsedByStates.Contains(texture.Name))
                {
                    list12.Add(new FsmTexture(texture));
                }
            }
            foreach (FsmString str in variables.StringVariables)
            {
                if (variablesUsedByStates.Contains(str.Name))
                {
                    list13.Add(new FsmString(str));
                }
            }
            FsmVariables variables3 = new FsmVariables();
            variables3.FloatVariables = list2.ToArray();
            variables3.IntVariables = list3.ToArray();
            variables3.BoolVariables = list4.ToArray();
            variables3.GameObjectVariables = list5.ToArray();
            variables3.ColorVariables = list6.ToArray();
            variables3.Vector3Variables = list7.ToArray();
            variables3.RectVariables = list8.ToArray();
            variables3.StringVariables = list13.ToArray();
            variables3.QuaternionVariables = list9.ToArray();
            variables3.ObjectVariables = list10.ToArray();
            variables3.MaterialVariables = list11.ToArray();
            variables3.TextureVariables = list12.ToArray();
            return variables3;
        }

        private static FsmTransition CopyTransition(FsmTransition transiton)
        {
            FsmTransition transition2 = new FsmTransition();
            transition2.FsmEvent = new FsmEvent(transiton.EventName);
            transition2.ToState = transiton.ToState;
            transition2.ColorIndex = transiton.ColorIndex;
            transition2.LinkConstraint = transiton.LinkConstraint;
            transition2.LinkStyle = transiton.LinkStyle;
            return transition2;
        }

        private static FsmTransition[] CopyTransitions(IEnumerable<FsmTransition> transitions)
        {
            List<FsmTransition> list = new List<FsmTransition>();
            foreach (FsmTransition transition in transitions)
            {
                list.Add(CopyTransition(transition));
            }
            return list.ToArray();
        }

        private static FsmVariables CopyVariables(FsmVariables variables)
        {
            List<FsmFloat> list = new List<FsmFloat>();
            List<FsmInt> list2 = new List<FsmInt>();
            List<FsmBool> list3 = new List<FsmBool>();
            List<FsmGameObject> list4 = new List<FsmGameObject>();
            List<FsmColor> list5 = new List<FsmColor>();
            List<FsmVector3> list6 = new List<FsmVector3>();
            List<FsmRect> list7 = new List<FsmRect>();
            List<FsmQuaternion> list8 = new List<FsmQuaternion>();
            List<FsmObject> list9 = new List<FsmObject>();
            List<FsmMaterial> list10 = new List<FsmMaterial>();
            List<FsmTexture> list11 = new List<FsmTexture>();
            List<FsmString> list12 = new List<FsmString>();
            foreach (FsmFloat num in variables.FloatVariables)
            {
                list.Add(new FsmFloat(num));
            }
            foreach (FsmInt num2 in variables.IntVariables)
            {
                list2.Add(new FsmInt(num2));
            }
            foreach (FsmBool @bool in variables.BoolVariables)
            {
                list3.Add(new FsmBool(@bool));
            }
            foreach (FsmGameObject obj2 in variables.GameObjectVariables)
            {
                list4.Add(new FsmGameObject(obj2));
            }
            foreach (FsmColor color in variables.ColorVariables)
            {
                list5.Add(new FsmColor(color));
            }
            foreach (FsmVector3 vector in variables.Vector3Variables)
            {
                list6.Add(new FsmVector3(vector));
            }
            foreach (FsmRect rect in variables.RectVariables)
            {
                list7.Add(new FsmRect(rect));
            }
            foreach (FsmQuaternion quaternion in variables.QuaternionVariables)
            {
                list8.Add(new FsmQuaternion(quaternion));
            }
            foreach (FsmObject obj3 in variables.ObjectVariables)
            {
                list9.Add(new FsmObject(obj3));
            }
            foreach (FsmMaterial material in variables.MaterialVariables)
            {
                list10.Add(new FsmMaterial(material));
            }
            foreach (FsmTexture texture in variables.TextureVariables)
            {
                list11.Add(new FsmTexture(texture));
            }
            foreach (FsmString str in variables.StringVariables)
            {
                list12.Add(new FsmString(str));
            }
            FsmVariables variables3 = new FsmVariables();
            variables3.FloatVariables = list.ToArray();
            variables3.IntVariables = list2.ToArray();
            variables3.BoolVariables = list3.ToArray();
            variables3.GameObjectVariables = list4.ToArray();
            variables3.ColorVariables = list5.ToArray();
            variables3.Vector3Variables = list6.ToArray();
            variables3.RectVariables = list7.ToArray();
            variables3.StringVariables = list12.ToArray();
            variables3.QuaternionVariables = list8.ToArray();
            variables3.ObjectVariables = list9.ToArray();
            variables3.MaterialVariables = list10.ToArray();
            variables3.TextureVariables = list11.ToArray();
            return variables3;
        }

        private static void CreateClipboard()
        {
            clipboard = (FsmTemplate) ScriptableObject.CreateInstance(typeof(FsmTemplate));
        }

        private static FsmTemplate CreateTemplate()
        {
            string str = EditorUtility.SaveFilePanel("保存模板", "Assets/TrainRes/Templates/", "template", "asset");
            if (str.Length == 0)
            {
                return null;
            }
            FsmTemplate asset = (FsmTemplate) ScriptableObject.CreateInstance(typeof(FsmTemplate));
            asset.fsm = new Fsm();
            asset.Category = "General";
            AssetDatabase.CreateAsset(asset, str.Substring(str.IndexOf("Assets/")));
            return asset;
        }

        public static void CreateTemplate(Fsm fsm)
        {
            FsmTemplate template = CreateTemplate();
            if (template != null)
            {
                CopyFsmToTemplate(fsm, template);
                EditorUtility.SetDirty(template);
            }
        }

        public static void CreateTemplate(List<FsmState> states)
        {
            FsmTemplate template = CreateTemplate();
            if (template != null)
            {
                CopyStatesToTemplate(states, template);
                EditorUtility.SetDirty(template);
            }
        }

        public void DeleteAction(FsmState state, FsmStateAction action)
        {
            if ((state != null) && (action != null))
            {
                FsmEditor.RegisterUndo("删除动作");
                state.Actions = TriangleGames.TrainResEditor.ArrayUtility.Remove<FsmStateAction>(state.Actions, action);
                FsmEditor.ResetKeyboard();
                state.SaveActions();
                FsmEditor.SetFsmDirty(true, false);
            }
        }

        public void DeleteActions(FsmState state, IEnumerable<FsmStateAction> actions, [Optional, DefaultParameterValue(true)] bool undo)
        {
            if ((state != null) && (actions != null))
            {
                if (undo)
                {
                    FsmEditor.RegisterUndo("删除动作");
                }
                foreach (FsmStateAction action in actions)
                {
                    state.Actions = TriangleGames.TrainResEditor.ArrayUtility.Remove<FsmStateAction>(state.Actions, action);
                }
                FsmEditor.ResetKeyboard();
                state.SaveActions();
                FsmEditor.SetFsmDirty(true, false);
            }
        }

        public void DeleteEvent(FsmEvent fsmEvent)
        {
            if (fsmEvent != null)
            {
                FsmEditor.RegisterUndo("删除事件");
                this.DeleteEvent(SelectedFsm, fsmEvent);
                UpdateAllStateSizes();
                FsmEditor.ResetKeyboard();
                FsmEditor.SetFsmDirty(true, false);
            }
        }

        public void DeleteEvent(Fsm fsm, FsmEvent fsmEvent)
        {
            if ((fsm != null) && !FsmEvent.IsNullOrEmpty(fsmEvent))
            {
                this.DeleteEvent(fsm, fsmEvent.Name);
            }
        }

        public void DeleteEvent(Fsm fsm, string fsmEventName)
        {
            if ((fsm != null) && !string.IsNullOrEmpty(fsmEventName))
            {
                List<FsmEvent> list = new List<FsmEvent>();
                foreach (FsmEvent event2 in fsm.Events)
                {
                    if (event2.Name != fsmEventName)
                    {
                        list.Add(event2);
                    }
                }
                fsm.Events = list.ToArray();
                List<FsmEvent> list2 = new List<FsmEvent>();
                foreach (FsmEvent event3 in fsm.ExposedEvents)
                {
                    if (event3.Name != fsmEventName)
                    {
                        list2.Add(event3);
                    }
                }
                fsm.ExposedEvents = list2;
                foreach (FsmTransition transition in fsm.GlobalTransitions)
                {
                    if (transition.EventName == fsmEventName)
                    {
                        transition.FsmEvent = null;
                    }
                }
                foreach (FsmState state in fsm.States)
                {
                    foreach (FsmTransition transition2 in state.Transitions)
                    {
                        if (transition2.EventName == fsmEventName)
                        {
                            transition2.FsmEvent = null;
                        }
                    }
                    foreach (FsmStateAction action in state.Actions)
                    {
                        this.DeleteEvent(state, action, fsmEventName);
                    }
                }
                FsmEditor.SetFsmDirty(fsm, true, false);
            }
        }

        public void DeleteEvent(object obj, string fsmEventName)
        {
            if ((obj != null) && !string.IsNullOrEmpty(fsmEventName))
            {
                foreach (FieldInfo info in ActionData.GetFields(obj.GetType()))
                {
                    System.Type fieldType = info.FieldType;
                    object obj2 = info.GetValue(obj);
                    if ((obj2 != null) && (fieldType == typeof(FsmEvent)))
                    {
                        FsmEvent event2 = (FsmEvent) obj2;
                        if (event2.Name == fsmEventName)
                        {
                            info.SetValue(obj, null);
                        }
                    }
                }
            }
        }

        public void DeleteEvent(FsmState state, FsmStateAction action, string fsmEventName)
        {
            if (((state != null) && (action != null)) && !string.IsNullOrEmpty(fsmEventName))
            {
                this.DeleteEvent(action, fsmEventName);
                state.SaveActions();
                FsmEditor.SetFsmDirty(state.Fsm, true, false);
            }
        }

        public void DeleteEventFromAll(FsmEvent fsmEvent)
        {
            if (!FsmEvent.IsNullOrEmpty(fsmEvent))
            {
                FsmEditor.RegisterSceneUndo("删除所有状态机事件");
                if (FsmEditorSettings.LoadAllPrefabs)
                {
                    FsmEditorUtility.LoadAllPrefabsInProject();
                }
                foreach (Fsm fsm in FsmEditor.FsmList)
                {
                    if (FsmEditorUtility.ShouldModify(fsm))
                    {
                        this.DeleteEvent(fsm, fsmEvent);
                    }
                }
            }
        }

        public void DeleteGlobalTransition(FsmTransition transition)
        {
            FsmEditor.RegisterUndo("删除全局过渡");
            FsmState transitionState = GetTransitionState(SelectedFsm, transition);
            SelectedFsm.GlobalTransitions = TriangleGames.TrainResEditor.ArrayUtility.Remove<FsmTransition>(SelectedFsm.GlobalTransitions, transition);
            UpdateStateSize(transitionState);
            FsmEditor.EventManager.UpdateUseCount();
            FsmEditor.ResetKeyboard();
            FsmEditor.SetFsmDirty(true, false);
        }

        public bool DeleteState(FsmState state, bool warning)
        {
            if (warning && !EditorUtility.DisplayDialog("删除状态", "你确定?", "确定", "取消"))
            {
                return false;
            }
            FsmEditor.RegisterUndo("删除状态");
            this.DoDeleteState(state);
            return true;
        }

        public bool DeleteStates(List<FsmState> states, bool warning)
        {
            if (warning && !EditorUtility.DisplayDialog("删除多个状态", "你确定?", "确定", "取消"))
            {
                return false;
            }
            FsmEditor.RegisterUndo("删除状态");
            foreach (FsmState state in states)
            {
                this.DoDeleteState(state);
            }
            return true;
        }

        public void DeleteTransition(FsmState state, FsmTransition transition)
        {
            FsmEditor.RegisterUndo("删除变换");
            state.Transitions = TriangleGames.TrainResEditor.ArrayUtility.Remove<FsmTransition>(state.Transitions, transition);
            UpdateStateSize(state);
            FsmEditor.EventManager.UpdateUseCount();
            FsmEditor.SetFsmDirty(true, false);
        }

        private static TrainResFSMCore DoAddFsmComponent(GameObject go)
        {
            TrainResFSMCore rfsm = go.AddComponent("TrainResFSM") as TrainResFSMCore;
            FsmEditor.RebuildFsmList();
            return rfsm;
        }

        private static Fsm DoAddTemplate(GameObject go, FsmTemplate fsmTemplate)
        {
            if ((fsmTemplate == null) || (go == null))
            {
                return null;
            }
            TrainResFSMCore rfsm = DoAddFsmComponent(go);
            rfsm.Fsm.Name = fsmTemplate.fsm.Name;
            rfsm.Fsm.States = CopyStates(fsmTemplate.fsm.States);
            rfsm.Fsm.GlobalTransitions = CopyTransitions(fsmTemplate.fsm.GlobalTransitions);
            rfsm.Fsm.Events = CopyEvents(fsmTemplate.fsm.Events);
            rfsm.Fsm.Variables = CopyVariables(fsmTemplate.fsm.Variables);
            rfsm.Fsm.Description = fsmTemplate.fsm.Description;
            rfsm.Fsm.Watermark = fsmTemplate.fsm.Watermark;
            rfsm.Fsm.StartState = fsmTemplate.fsm.StartState;
            bool flag = false;
            foreach (FsmState state in rfsm.Fsm.States)
            {
                TranslateState(state, new Vector2(100f, 100f));
                if (state.Name == rfsm.Fsm.StartState)
                {
                    flag = true;
                }
            }
            if (!flag)
            {
                EditorUtility.DisplayDialog("设置开始状态", "模板没有定义开始状态...\n请设置第一个状态为开始状态.", "确定");
                rfsm.Fsm.StartState = rfsm.Fsm.States[0].Name;
            }
            return rfsm.Fsm;
        }

        private static Fsm DoAddTemplateToSelected(FsmTemplate fsmTemplate)
        {
            Fsm fsm = null;
            foreach (GameObject obj2 in Selection.gameObjects)
            {
                fsm = DoAddTemplate(obj2, fsmTemplate);
            }
            FsmEditor.RebuildFsmList();
            return fsm;
        }

        private void DoDeleteState(FsmState state)
        {
            if (state == null)
            {
                Debug.LogError("尝试删除不存在的状态!");
            }
            else if (this.IsStartState(state))
            {
                EditorApplication.Beep();
                EditorUtility.DisplayDialog("删除状态", "不能删除开始状态!", "确定");
            }
            else
            {
                foreach (FsmState state2 in SelectedFsm.States)
                {
                    foreach (FsmTransition transition in state2.Transitions)
                    {
                        if (transition.ToState == state.Name)
                        {
                            transition.ToState = "";
                        }
                    }
                }
                foreach (FsmTransition transition2 in SelectedFsm.GlobalTransitions)
                {
                    if (transition2.ToState == state.Name)
                    {
                        this.DeleteGlobalTransition(transition2);
                    }
                }
                if (SelectedFsm.StartState == state.Name)
                {
                    SelectedFsm.StartState = "";
                }
                foreach (FsmTransition transition3 in state.Transitions)
                {
                    this.DeleteTransition(state, transition3);
                }
                SelectedFsm.States = TriangleGames.TrainResEditor.ArrayUtility.Remove<FsmState>(SelectedFsm.States, state);
                FsmEditor.GraphView.UpdateCanvasSize();
                FsmEditor.SetFsmDirty(true, false);
            }
        }

        public void EnableAction(FsmStateAction action, bool enabledState)
        {
            if (action != null)
            {
                FsmEditor.RegisterUndo("启用动作");
                action.Enabled = enabledState;
                action.State.SaveActions();
                FsmEditor.SetFsmDirty(true, false);
            }
        }

        public void EnableAllActions(bool enabledState)
        {
            FsmEditor.RegisterUndo("启用全部动作");
            foreach (FsmStateAction action in SelectedState.Actions)
            {
                action.Enabled = enabledState;
                action.State.SaveActions();
            }
            FsmEditor.SetFsmDirty(true, false);
        }

        public FsmTransition FindTransitionToState(FsmState toState)
        {
            foreach (FsmTransition transition in SelectedFsm.GlobalTransitions)
            {
                if (transition.ToState == toState.Name)
                {
                    return transition;
                }
            }
            if (SelectedFsm.ActiveState != null)
            {
                foreach (FsmTransition transition2 in SelectedFsm.ActiveState.Transitions)
                {
                    if (transition2.ToState == toState.Name)
                    {
                        return transition2;
                    }
                }
            }
            return null;
        }

        private static string GenerateCopyName(FsmState state)
        {
            if (!StateNameExists(state, state.Name))
            {
                return state.Name;
            }
            int length = state.Name.LastIndexOf(" - Copy");
            if (length != -1)
            {
                return GenerateUniqueStateName(state, state.Name.Substring(0, length) + " - Copy");
            }
            return GenerateUniqueStateName(state, state.Name + " - Copy");
        }

        private static string GenerateUniqueStateName(FsmState state, string newNameRoot)
        {
            int num = 1;
            string name = newNameRoot + " " + num.ToString(CultureInfo.InvariantCulture);
            while (StateNameExists(state, name))
            {
                name = newNameRoot + " " + num++.ToString(CultureInfo.InvariantCulture);
            }
            return name;
        }

        public List<FsmTransition> GetGlobalTransitions(FsmState state)
        {
            List<FsmTransition> list = new List<FsmTransition>();
            foreach (FsmTransition transition in SelectedFsm.GlobalTransitions)
            {
                if (transition.ToState == state.Name)
                {
                    list.Add(transition);
                }
            }
            return list;
        }

        public FsmState GetStartState()
        {
            if (SelectedFsm != null)
            {
                return SelectedFsm.GetState(SelectedFsm.StartState);
            }
            return null;
        }

        public int GetTransitionIndex(FsmState state, FsmTransition transition)
        {
            int num = 0;
            foreach (FsmTransition transition2 in state.Transitions)
            {
                if (transition2 == transition)
                {
                    return num;
                }
                num++;
            }
            return -1;
        }

        private static FsmState GetTransitionState(Fsm fsm, FsmTransition transition)
        {
            if ((fsm != null) && (transition != null))
            {
                foreach (FsmTransition transition2 in fsm.GlobalTransitions)
                {
                    if (transition2 == transition)
                    {
                        return fsm.GetState(transition2.ToState);
                    }
                }
                foreach (FsmState state in fsm.States)
                {
                    foreach (FsmTransition transition3 in state.Transitions)
                    {
                        if (transition3 == transition)
                        {
                            return state;
                        }
                    }
                }
            }
            return null;
        }

        public bool HasGlobalTransition(FsmState state)
        {
            foreach (FsmTransition transition in SelectedFsm.GlobalTransitions)
            {
                if (transition.ToState == state.Name)
                {
                    return true;
                }
            }
            return false;
        }

        public FsmStateAction InsertAction(FsmState state, System.Type actionType, FsmStateAction beforeAction)
        {
            if (state == null)
            {
                return null;
            }
            if (beforeAction == null)
            {
                return this.AddAction(state, actionType);
            }
            FsmEditor.RegisterUndo("插入动作");
            FsmStateAction item = (FsmStateAction) Activator.CreateInstance(actionType);
            int actionIndex = FsmEditorUtility.GetActionIndex(FsmEditor.SelectedState, beforeAction);
            if (actionIndex == -1)
            {
                return this.AddAction(state, actionType);
            }
            List<FsmStateAction> list = new List<FsmStateAction>(state.Actions);
            list.Insert(actionIndex, item);
            state.Actions = list.ToArray();
            item.Init(state);
            item.Reset();
            state.SaveActions();
            FsmEditor.SetFsmDirty(true, false);
            return item;
        }

        public bool IsStartState(FsmState fsmState)
        {
            if (fsmState == null)
            {
                return false;
            }
            return (SelectedFsm.GetState(SelectedFsm.StartState) == fsmState);
        }

        public void MoveActionAfter(FsmState state, FsmStateAction action, FsmStateAction afterAction)
        {
            if (((state != null) && (action != null)) && (afterAction != null))
            {
                List<FsmStateAction> list = new List<FsmStateAction>(state.Actions);
                list.Remove(action);
                int index = list.IndexOf(afterAction);
                if (index < 0)
                {
                    index = list.Count - 1;
                }
                if (index == (list.Count - 1))
                {
                    list.Add(action);
                }
                else
                {
                    list.Insert(index + 1, action);
                }
                state.Actions = list.ToArray();
                state.SaveActions();
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        public void MoveActionBefore(FsmState state, FsmStateAction action, FsmStateAction beforeAction)
        {
            if (((state != null) && (action != null)) && (beforeAction != null))
            {
                List<FsmStateAction> list = new List<FsmStateAction>(state.Actions);
                list.Remove(action);
                int index = list.IndexOf(beforeAction);
                if (index < 0)
                {
                    index = 0;
                }
                list.Insert(index, action);
                state.Actions = list.ToArray();
                state.SaveActions();
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        public void MoveActionDown(FsmState state, FsmStateAction action)
        {
            if ((state != null) && (action != null))
            {
                List<FsmStateAction> list = new List<FsmStateAction>(state.Actions);
                int index = list.IndexOf(action);
                if (index != (state.Actions.Length - 1))
                {
                    FsmEditor.RegisterUndo("向下移动动作");
                    list.Remove(action);
                    list.Insert(index + 1, action);
                    state.Actions = list.ToArray();
                    state.SaveActions();
                    FsmEditor.SetFsmDirty(false, false);
                }
            }
        }

        public void MoveActionToBottom(FsmState state, FsmStateAction action)
        {
            if ((state != null) && (action != null))
            {
                List<FsmStateAction> list = new List<FsmStateAction>(state.Actions);
                if (list.IndexOf(action) != (state.Actions.Length - 1))
                {
                    FsmEditor.RegisterUndo("移动动作到底部");
                    list.Remove(action);
                    list.Add(action);
                    state.Actions = list.ToArray();
                    state.SaveActions();
                    FsmEditor.SetFsmDirty(false, false);
                }
            }
        }

        public void MoveActionToTop(FsmState state, FsmStateAction action)
        {
            if ((state != null) && (action != null))
            {
                List<FsmStateAction> list = new List<FsmStateAction>(state.Actions);
                if (list.IndexOf(action) != 0)
                {
                    FsmEditor.RegisterUndo("移动动作到顶部");
                    list.Remove(action);
                    list.Insert(0, action);
                    state.Actions = list.ToArray();
                    state.SaveActions();
                    FsmEditor.SetFsmDirty(false, false);
                }
            }
        }

        public void MoveActionUp(FsmState state, FsmStateAction action)
        {
            if ((state != null) && (action != null))
            {
                List<FsmStateAction> list = new List<FsmStateAction>(state.Actions);
                int index = list.IndexOf(action);
                if (index != 0)
                {
                    FsmEditor.RegisterUndo("向上移动动作");
                    list.Remove(action);
                    list.Insert(index - 1, action);
                    state.Actions = list.ToArray();
                    state.SaveActions();
                    FsmEditor.SetFsmDirty(false, false);
                }
            }
        }

        public void OnDestroy()
        {
        }

        public void OpenAction(FsmStateAction action, bool openState)
        {
            if (action != null)
            {
                action.IsOpen = openState;
                action.State.SaveActions();
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        public void OpenAllActions(bool openState)
        {
            foreach (FsmStateAction action in SelectedState.Actions)
            {
                action.IsOpen = openState;
                action.State.SaveActions();
            }
            FsmEditor.SetFsmDirty(false, false);
        }

        public static List<FsmStateAction> PasteActionsFromTemplate(FsmTemplate template, FsmState state, int atIndex, [Optional, DefaultParameterValue(true)] bool undo)
        {
            if (((atIndex == -1) || (template == null)) || (template.fsm == null))
            {
                return null;
            }
            FsmState state2 = CopyState(template.fsm.States[0]);
            if (state2 == null)
            {
                return null;
            }
            if (undo)
            {
                FsmEditor.RegisterUndo("粘贴动作");
            }
            state2.Fsm = template.fsm;
            state2.LoadActions();
            List<FsmStateAction> collection = new List<FsmStateAction>();
            int actionCount = state2.ActionData.ActionCount;
            for (int i = 0; i < actionCount; i++)
            {
                FsmStateAction item = state2.ActionData.CreateAction(state2, i);
                collection.Add(item);
            }
            List<FsmStateAction> list2 = new List<FsmStateAction>(state.Actions);
            list2.InsertRange(atIndex, collection);
            state.Actions = list2.ToArray();
            state.SaveActions();
            PasteVariables(SelectedFsm, template.fsm.Variables);
            SelectedFsm.Reinitialize();
            FsmEditor.SetFsmDirty(true, false);
            collection = new List<FsmStateAction>();
            for (int j = atIndex; j < (atIndex + actionCount); j++)
            {
                collection.Add(SelectedState.Actions[j]);
            }
            return collection;
        }

        public static Fsm PasteFsmToSelected()
        {
            if (clipboard == null)
            {
                return null;
            }
            GameObject[] gameObjects = Selection.gameObjects;
            if (gameObjects.Length == 0)
            {
                return null;
            }
            if ((gameObjects.Length > 1) && !EditorUtility.DisplayDialog("粘贴状态机", "是否粘贴状态机到多个对象?", "是", "否"))
            {
                return null;
            }
            FsmEditor.RegisterSceneUndo("粘贴状态机到选定对象");
            return DoAddTemplateToSelected(clipboard);
        }

        public List<FsmState> PasteStatesFromClipboard(Vector2 position)
        {
            return this.PasteStatesFromTemplate(clipboard, position);
        }

        public List<FsmState> PasteStatesFromTemplate(FsmTemplate template, Vector2 position)
        {
            if (template.fsm.States.Length == 0)
            {
                return null;
            }
            FsmEditor.RegisterUndo("粘贴状态");
            List<FsmState> collection = new List<FsmState>();
            foreach (FsmState state in template.fsm.States)
            {
                collection.Add(CopyState(state));
            }
            List<FsmTransition> list2 = new List<FsmTransition>();
            foreach (FsmTransition transition in template.fsm.GlobalTransitions)
            {
                list2.Add(CopyTransition(transition));
            }
            List<FsmState> list3 = new List<FsmState>(SelectedFsm.States);
            list3.AddRange(collection);
            SelectedFsm.States = list3.ToArray();
            foreach (FsmState state2 in collection)
            {
                state2.Fsm = SelectedFsm;
                string str = GenerateCopyName(state2);
                if ((template.fsm.StartState == state2.Name) && EditorUtility.DisplayDialog("替换开始状态?", "模板定义了一个开始状态. 你是否想替换当前开始状态?", "是", "否"))
                {
                    SelectedFsm.StartState = str;
                }
                foreach (FsmState state3 in collection)
                {
                    foreach (FsmTransition transition2 in state3.Transitions)
                    {
                        if (!StateSelectionContainsState(collection, transition2.ToState))
                        {
                            transition2.ToState = "";
                        }
                        if (transition2.ToState == state2.Name)
                        {
                            transition2.ToState = str;
                        }
                    }
                }
                foreach (FsmTransition transition3 in list2)
                {
                    if (transition3.ToState == state2.Name)
                    {
                        transition3.ToState = str;
                    }
                }
                state2.Name = str;
                TranslateState(state2, position);
            }
            list2.AddRange(SelectedFsm.GlobalTransitions);
            SelectedFsm.GlobalTransitions = list2.ToArray();
            foreach (FsmState state4 in collection)
            {
                UpdateStateSize(state4);
            }
            PasteVariables(SelectedFsm, template.fsm.Variables);
            SelectedFsm.Reinitialize();
            FsmEditor.SetFsmDirty(true, false);
            FsmEditor.ResetKeyboard();
            return collection;
        }

        private static void PasteVariables(Fsm fsm, FsmVariables variables)
        {
            List<FsmVariable> fsmVariableList = FsmVariable.GetFsmVariableList(variables, null);
            List<FsmVariable> list2 = FsmVariable.GetFsmVariableList(fsm.Variables, null);
            foreach (FsmVariable variable in fsmVariableList)
            {
                if (FsmVariable.VariableNameUsed(list2, variable.Name))
                {
                    if (FsmVariable.GetVariableType(list2, variable.Name) != variable.Type)
                    {
                        Debug.LogError("变量已经存在并且类型不同: " + variable.Name);
                    }
                }
                else
                {
                    switch (variable.Type)
                    {
                        case VariableType.Float:
                            fsm.Variables.FloatVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmFloat>(fsm.Variables.FloatVariables, new FsmFloat((FsmFloat) variable.NamedVar));
                            break;

                        case VariableType.Int:
                            fsm.Variables.IntVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmInt>(fsm.Variables.IntVariables, new FsmInt((FsmInt) variable.NamedVar));
                            break;

                        case VariableType.Bool:
                            fsm.Variables.BoolVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmBool>(fsm.Variables.BoolVariables, new FsmBool((FsmBool) variable.NamedVar));
                            break;

                        case VariableType.GameObject:
                            fsm.Variables.GameObjectVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmGameObject>(fsm.Variables.GameObjectVariables, new FsmGameObject((FsmGameObject) variable.NamedVar));
                            break;

                        case VariableType.String:
                            fsm.Variables.StringVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmString>(fsm.Variables.StringVariables, new FsmString((FsmString) variable.NamedVar));
                            break;

                        case VariableType.Vector3:
                            fsm.Variables.Vector3Variables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmVector3>(fsm.Variables.Vector3Variables, new FsmVector3((FsmVector3) variable.NamedVar));
                            break;

                        case VariableType.Color:
                            fsm.Variables.ColorVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmColor>(fsm.Variables.ColorVariables, new FsmColor((FsmColor) variable.NamedVar));
                            break;

                        case VariableType.Rect:
                            fsm.Variables.RectVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmRect>(fsm.Variables.RectVariables, new FsmRect((FsmRect) variable.NamedVar));
                            break;

                        case VariableType.Material:
                            fsm.Variables.MaterialVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmMaterial>(fsm.Variables.MaterialVariables, new FsmMaterial((FsmMaterial) variable.NamedVar));
                            break;

                        case VariableType.Texture:
                            fsm.Variables.TextureVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmTexture>(fsm.Variables.TextureVariables, new FsmTexture((FsmTexture) variable.NamedVar));
                            break;

                        case VariableType.Quaternion:
                            fsm.Variables.QuaternionVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmQuaternion>(fsm.Variables.QuaternionVariables, new FsmQuaternion((FsmQuaternion) variable.NamedVar));
                            break;

                        case VariableType.Object:
                            fsm.Variables.ObjectVariables = TriangleGames.TrainResEditor.ArrayUtility.Add<FsmObject>(fsm.Variables.ObjectVariables, new FsmObject((FsmObject) variable.NamedVar));
                            break;
                    }
                }
            }
        }

        public static void RemoveExposedEvent(Fsm fsm, FsmEvent fsmEvent)
        {
            List<FsmEvent> list = new List<FsmEvent>();
            foreach (FsmEvent event2 in fsm.ExposedEvents)
            {
                if (event2.Name == fsmEvent.Name)
                {
                    list.Add(event2);
                }
            }
            foreach (FsmEvent event3 in list)
            {
                fsm.ExposedEvents.Remove(event3);
            }
            FsmEditor.SetFsmDirty(false, false);
        }

        public static void RemoveVariableUsage(NamedVariable variable)
        {
            List<FsmInfo> fsmInfoList = FsmInfo.FindVariableUsage(variable);
            foreach (FsmInfo info in fsmInfoList)
            {
                RemoveVariableUsageInField(info.action, info.field, variable);
            }
            foreach (Fsm fsm in FsmInfo.GetFsmList(fsmInfoList))
            {
                FsmEditor.SaveActions(fsm);
            }
        }

        public static void RemoveVariableUsageInArray(Array array, System.Type type, int elementIndex, NamedVariable variable)
        {
            object obj2 = array.GetValue(elementIndex);
            if (obj2 != null)
            {
                if (type.IsSubclassOf(typeof(NamedVariable)))
                {
                    NamedVariable variable2 = (NamedVariable) obj2;
                    if (variable2.UseVariable && (variable2 == variable))
                    {
                        array.SetValue(null, elementIndex);
                    }
                }
                if (type.IsClass)
                {
                    RemoveVariableUsageInObject(obj2, variable);
                }
            }
        }

        public static void RemoveVariableUsageInField(object obj, FieldInfo field, NamedVariable variable)
        {
            System.Type fieldType = field.FieldType;
            object obj2 = field.GetValue(obj);
            if (obj2 != null)
            {
                if (fieldType.IsSubclassOf(typeof(NamedVariable)))
                {
                    NamedVariable variable2 = (NamedVariable) obj2;
                    if (variable2.UseVariable && (variable2 == variable))
                    {
                        object obj3 = Activator.CreateInstance(fieldType);
                        fieldType.GetProperty("UseVariable").SetValue(obj3, true, null);
                        field.SetValue(obj, obj3);
                    }
                }
                if (fieldType.IsArray)
                {
                    Array array = (Array) obj2;
                    System.Type elementType = fieldType.GetElementType();
                    for (int i = 0; i < array.Length; i++)
                    {
                        RemoveVariableUsageInArray(array, elementType, i, variable);
                    }
                }
                if (fieldType.IsClass)
                {
                    RemoveVariableUsageInObject(obj2, variable);
                }
            }
        }

        public static void RemoveVariableUsageInObject(object obj, NamedVariable variable)
        {
            if (obj != null)
            {
                foreach (FieldInfo info in obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
                {
                    RemoveVariableUsageInField(obj, info, variable);
                }
            }
        }

        public void RenameAction(FsmStateAction action, string newName)
        {
            if (action != null)
            {
                FsmEditor.RegisterUndo("重命名动作");
                action.Name = newName;
                action.State.SaveActions();
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        public void RenameEvent(string oldEventName, string newEventName)
        {
            FsmEditor.RegisterSceneUndo("重命名事件");
            if (FsmEditorSettings.LoadAllPrefabs)
            {
                FsmEditorUtility.LoadAllPrefabsInProject();
            }
            List<FsmInfo> fsmInfoList = FsmInfo.FindActionsUsingEvent(oldEventName);
            foreach (FsmInfo info in fsmInfoList)
            {
                RenameEventInField(info.action, info.field, oldEventName, newEventName);
            }
            foreach (Fsm fsm in FsmInfo.GetFsmList(fsmInfoList))
            {
                FsmEditor.SaveActions(fsm);
            }
            foreach (FsmInfo info2 in FsmInfo.FindTransitionsUsingEvent(oldEventName))
            {
                info2.transition.FsmEvent.Name = newEventName;
            }
            foreach (Fsm fsm2 in FsmEditor.FsmList)
            {
                foreach (FsmEvent event2 in fsm2.Events)
                {
                    if (event2.Name == oldEventName)
                    {
                        event2.Name = newEventName;
                    }
                }
                UpdateStateSizes(fsm2);
                FsmEditor.SetFsmDirty(fsm2, true, false);
            }
            FsmEvent event3 = FsmEvent.FindEvent(oldEventName);
            if (event3 != null)
            {
                event3.Name = newEventName;
            }
            if (FsmEvent.globalEvents.Contains(oldEventName))
            {
                FsmEvent.globalEvents.Remove(oldEventName);
                if (!FsmEvent.globalEvents.Contains(newEventName))
                {
                    FsmEvent.globalEvents.Add(newEventName);
                }
            }
        }

        public void RenameEvent(Fsm fsmTarget, string oldEventName, string newEventName)
        {
            FsmEditor.RegisterSceneUndo("重命名事件");
            if (FsmEditorSettings.LoadAllPrefabs)
            {
                FsmEditorUtility.LoadAllPrefabsInProject();
            }
            foreach (FsmInfo info in FsmInfo.FindActionsUsingEvent(fsmTarget, oldEventName))
            {
                RenameEventInField(info.action, info.field, oldEventName, newEventName);
            }
            FsmEditor.SaveActions(fsmTarget);
            foreach (FsmInfo info2 in FsmInfo.FindTransitionsUsingEvent(fsmTarget, oldEventName))
            {
                info2.transition.FsmEvent.Name = newEventName;
            }
            foreach (FsmEvent event2 in fsmTarget.Events)
            {
                if (event2.Name == oldEventName)
                {
                    event2.Name = newEventName;
                }
            }
            foreach (FsmEvent event3 in fsmTarget.ExposedEvents)
            {
                if (event3.Name == oldEventName)
                {
                    event3.Name = newEventName;
                }
            }
            UpdateStateSizes(fsmTarget);
            FsmEditor.SetFsmDirty(fsmTarget, true, false);
            if (FsmEvent.globalEvents.Contains(oldEventName) && !FsmEvent.globalEvents.Contains(newEventName))
            {
                FsmEvent.globalEvents.Add(newEventName);
            }
        }

        public static void RenameEventInArray(Array array, int elementIndex, string oldEventName, string newEventName)
        {
            object obj2 = array.GetValue(elementIndex);
            if (obj2 != null)
            {
                FsmEvent event2 = obj2 as FsmEvent;
                if ((event2 != null) && (event2.Name == oldEventName))
                {
                    event2.Name = newEventName;
                    array.SetValue(event2, elementIndex);
                }
            }
        }

        public static void RenameEventInField(object obj, FieldInfo field, string oldEventName, string newEventName)
        {
            System.Type fieldType = field.FieldType;
            object obj2 = field.GetValue(obj);
            if (obj2 != null)
            {
                if (fieldType == typeof(FsmEvent))
                {
                    FsmEvent event2 = (FsmEvent) obj2;
                    if (event2.Name == oldEventName)
                    {
                        event2.Name = newEventName;
                        field.SetValue(obj, event2);
                    }
                }
                if (fieldType.IsArray)
                {
                    Array array = (Array) obj2;
                    if (fieldType.GetElementType() == typeof(FsmEvent))
                    {
                        for (int i = 0; i < array.Length; i++)
                        {
                            RenameEventInArray(array, i, oldEventName, newEventName);
                        }
                    }
                }
            }
        }

        public static void RenameEventInObject(object obj, string oldEventName, string newEventName)
        {
            if (obj != null)
            {
                foreach (FieldInfo info in obj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
                {
                    RenameEventInField(obj, info, oldEventName, newEventName);
                }
            }
        }

        public bool RenameState(FsmState state, string newName)
        {
            string message = this.ValidateNewStateName(state, newName);
            if (message != "")
            {
                EditorUtility.DisplayDialog("不能重命名状态!", message, "确定");
                return false;
            }
            FsmEditor.RegisterUndo("重命名状态");
            foreach (FsmState state2 in SelectedFsm.States)
            {
                foreach (FsmTransition transition in state2.Transitions)
                {
                    if (transition.ToState == state.Name)
                    {
                        transition.ToState = newName;
                    }
                }
            }
            foreach (FsmTransition transition2 in SelectedFsm.GlobalTransitions)
            {
                if (transition2.ToState == state.Name)
                {
                    transition2.ToState = newName;
                }
            }
            if (SelectedFsm.StartState == state.Name)
            {
                SelectedFsm.StartState = newName;
            }
            state.Name = newName;
            UpdateStateSize(state);
            FsmEditor.SetFsmDirty(true, false);
            return true;
        }

        public void ResetAction(FsmStateAction action)
        {
            if (action != null)
            {
                FsmEditor.RegisterUndo("重置动作");
                action.Reset();
                action.State.SaveActions();
                FsmEditor.SetFsmDirty(true, false);
            }
        }

        public void ResetActionName(FsmStateAction action)
        {
            if (action != null)
            {
                FsmEditor.RegisterUndo("重置动作名称");
                action.Name = null;
                action.State.SaveActions();
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        public void SetEventIsGlobal(FsmEvent fsmEvent, bool isGlobal)
        {
            if (fsmEvent != null)
            {
                FsmEditor.RegisterGlobalsUndo("修改事件全局设置");
                fsmEvent.IsGlobal = isGlobal;
                FsmEditor.SaveGlobals();
            }
        }

        public void SetLinkConstraint(FsmTransition transition, FsmTransition.CustomLinkConstraint linkConstraint)
        {
            if (transition != null)
            {
                FsmEditor.RegisterUndo("设置链接约束");
                transition.LinkConstraint = linkConstraint;
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        public void SetLinkStyle(FsmTransition transition, FsmTransition.CustomLinkStyle linkStyle)
        {
            if (transition != null)
            {
                FsmEditor.RegisterUndo("设置链接风格");
                transition.LinkStyle = linkStyle;
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        public static void SetSelectedStatesColorIndex(int colorIndex)
        {
            FsmEditor.RegisterUndo("设置选定状态颜色");
            colorIndex = Mathf.Clamp(colorIndex, 0, Fsm.StateColors.Length - 1);
            foreach (FsmState state in FsmEditor.Selection.States)
            {
                state.ColorIndex = colorIndex;
            }
            FsmEditor.SetFsmDirty(false, false);
        }

        public void SetStartState(string state)
        {
            FsmEditor.RegisterUndo("设置开始状态");
            SelectedFsm.StartState = state;
            FsmEditor.SetFsmDirty(true, false);
        }

        public static void SetStateColorIndex(FsmState state, int colorIndex, [Optional, DefaultParameterValue(true)] bool undo)
        {
            if (state != null)
            {
                if (undo)
                {
                    FsmEditor.RegisterUndo("设置状态颜色");
                }
                colorIndex = Mathf.Clamp(colorIndex, 0, Fsm.StateColors.Length - 1);
                state.ColorIndex = colorIndex;
                FsmEditor.SetFsmDirty(state.Fsm, false, false);
            }
        }

        public static void SetTransitionColorIndex(Fsm fsm, FsmTransition transition, int colorIndex, [Optional, DefaultParameterValue(true)] bool undo)
        {
            if (transition != null)
            {
                if (undo)
                {
                    FsmEditor.RegisterUndo("设置变换颜色");
                }
                colorIndex = Mathf.Clamp(colorIndex, 0, Fsm.StateColors.Length - 1);
                transition.ColorIndex = colorIndex;
                FsmEditor.SetFsmDirty(fsm, false, false);
            }
        }

        public void SetTransitionEvent(FsmTransition transition, FsmEvent fsmEvent)
        {
            if (transition.FsmEvent != fsmEvent)
            {
                FsmEditor.RegisterUndo("设置变换事件");
                transition.FsmEvent = fsmEvent;
                UpdateStateSize(GetTransitionState(SelectedFsm, transition));
                FsmEditor.EventManager.UpdateUseCount();
                FsmEditor.SetFsmDirty(true, false);
            }
        }

        public void SetTransitionTarget(FsmTransition transition, string toState)
        {
            FsmEditor.RegisterUndo("设置变换目标");
            transition.ToState = toState;
            FsmEditor.SetFsmDirty(true, false);
        }

        private static bool StateNameExists(FsmState state, string name)
        {
            foreach (FsmState state2 in SelectedFsm.States)
            {
                if ((state2 != state) && (state2.Name == name))
                {
                    return true;
                }
            }
            return false;
        }

        private static bool StateSelectionContainsState(IEnumerable<FsmState> states, string stateName)
        {
            foreach (FsmState state in states)
            {
                if (state.Name == stateName)
                {
                    return true;
                }
            }
            return false;
        }

        public void ToggleBreakpoint(FsmState state)
        {
            if (state != null)
            {
                FsmEditor.RegisterUndo("切换断点");
                state.IsBreakpoint = !state.IsBreakpoint;
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        public void ToggleLinkStyle(FsmTransition transition)
        {
            if (transition != null)
            {
                FsmEditor.RegisterUndo("设置链接风格");
                switch (transition.LinkStyle)
                {
                    case FsmTransition.CustomLinkStyle.Default:
                        transition.LinkStyle = (FsmEditorSettings.GraphViewLinkStyle == GraphViewLinkStyle.BezierLinks) ? FsmTransition.CustomLinkStyle.Circuit : FsmTransition.CustomLinkStyle.Bezier;
                        break;

                    case FsmTransition.CustomLinkStyle.Bezier:
                        transition.LinkStyle = FsmTransition.CustomLinkStyle.Circuit;
                        break;

                    case FsmTransition.CustomLinkStyle.Circuit:
                        transition.LinkStyle = FsmTransition.CustomLinkStyle.Bezier;
                        break;
                }
                FsmEditor.SetFsmDirty(false, false);
            }
        }

        public static void TranslateState(FsmState state, Vector2 offset)
        {
            Vector2 position = new Vector2(state.Position.x, state.Position.y) + offset;
            UpdateStatePosition(state, position);
        }

        public static void UpdateAllStateSizes()
        {
            foreach (Fsm fsm in FsmEditor.FsmList)
            {
                UpdateStateSizes(fsm);
            }
            FsmEditor.Repaint(false);
        }

        public static void UpdateStatePosition(FsmState state, Vector2 position)
        {
            Rect rect2 = new Rect(state.Position);
            rect2.x = Mathf.Clamp(position.x, 0f, 20000f);
            rect2.y = Mathf.Clamp(position.y, 0f, 20000f);
            Rect rect = rect2;
            state.Position = rect;
        }

        public static void UpdateStateSize(FsmState state)
        {
            if (state != null)
            {
                Rect rect2 = new Rect(state.Position);
                rect2.width = CalculateStateWidth(state);
                Rect rect = rect2;
                int num = state.Transitions.Length + 1;
                rect.height = num * 16f;
                state.Position = rect;
                UpdateStatePosition(state, new Vector2(state.Position.x, state.Position.y));
            }
        }

        public static void UpdateStateSizes(Fsm fsm)
        {
            if (fsm != null)
            {
                foreach (FsmState state in fsm.States)
                {
                    state.Fsm = fsm;
                    UpdateStateSize(state);
                }
            }
        }

        public string ValidateAddEvent(string newEventName)
        {
            if (!string.IsNullOrEmpty(newEventName))
            {
                if (newEventName.Replace(" ", "") == "")
                {
                    return "无效名称!";
                }
                foreach (FsmEvent event2 in FsmEditor.SelectedFsm.Events)
                {
                    if (event2.Name == newEventName)
                    {
                        return "事件已经被使用!";
                    }
                }
            }
            return "";
        }

        public string ValidateNewStateName(FsmState state, string newName)
        {
            if (string.IsNullOrEmpty(newName))
            {
                return "名称是空的!";
            }
            foreach (FsmState state2 in SelectedFsm.States)
            {
                if ((state2 != state) && (state2.Name == newName))
                {
                    return "名称已经在此状态机中使用!";
                }
            }
            if (newName.Length > 100)
            {
                return "名称太长!";
            }
            if (newName.Contains(@"\"))
            {
                return @"名称包含非法字符: \";
            }
            return "";
        }

        public string ValidateRenameEvent(FsmEvent fsmEvent, string newEventName)
        {
            if ((fsmEvent == null) || (newEventName == null))
            {
                return "无效名称!";
            }
            if ((fsmEvent.Name != newEventName) && (newEventName.Replace(" ", "") == ""))
            {
                return "无效名称!";
            }
            return "";
        }

        public static FsmTemplate Clipboard
        {
            get
            {
                return clipboard;
            }
            set
            {
                clipboard = value;
            }
        }

        public static int ClipboardNumStates
        {
            get
            {
                if (((clipboard != null) && (clipboard.fsm != null)) && (clipboard.fsm.States != null))
                {
                    return clipboard.fsm.States.Length;
                }
                return 0;
            }
        }

        private static Fsm SelectedFsm
        {
            get
            {
                return FsmEditor.SelectedFsm;
            }
        }

        private static FsmState SelectedState
        {
            get
            {
                return FsmEditor.SelectedState;
            }
        }
    }
}

